<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="建模数据编号" prop="constructNo">
        <el-input
          v-model="queryParams.constructNo"
          placeholder="请输入建模数据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="构建状态" prop="constructStateName">
        <el-select
          v-model="queryParams.constructStateCode"
          placeholder="请选择构建状态"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.construct_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成分名称" prop="constituentName">
        <el-input
          v-model="queryParams.constituentName"
          placeholder="请输入成分名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器编号" prop="instrumentNo">
        <el-input
          v-model="queryParams.instrumentNo"
          placeholder="请输入仪器编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器名称" prop="instrumentName">
        <el-input
          v-model="queryParams.instrumentName"
          placeholder="请输入仪器名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据构建人" prop="builderName">
        <el-input
          v-model="queryParams.builderName"
          placeholder="请输入数据构建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采样时间" prop="samplingTime">
        <el-date-picker
          clearable
          v-model="queryParams.samplingTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采样时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="isRowVisible">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:construct:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['model:construct:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['model:construct:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['model:construct:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="constructTable"
      v-loading="loading"
      :data="constructList"
      @selection-change="handleSelectionChange"
      style="max-height: 550px; overflow-y: auto;"
      height="550"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="建模数据编号" width="145" align="center" prop="constructNo" fixed />
      <el-table-column label="成分名称" align="center" prop="constituentName" />
      <el-table-column label="部门名称" align="center" prop="departmentName" />
      <el-table-column label="仪器编号" width="145" align="center" prop="instrumentNo" />
      <el-table-column label="仪器名称" align="center" prop="instrumentName" />
      <el-table-column
        label="采样时间"
        align="center"
        prop="samplingTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.samplingTime, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="构建状态"
        align="center"
        prop="constructStateName"
      >
        <template slot-scope="scope">
          <el-tag :type="getTagType(scope.row.constructStateName)">
            {{ scope.row.constructStateName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="环境光谱编号"
        width="145"
        align="center"
        prop="envSpectrumNo"
      />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column
        label="操作"
        align="center"
        v-if="isRowVisible"
        class-name="small-padding fixed-width"
        fixed="right"
        width="220"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['model:construct:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['model:construct:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleViewDetail(scope.row)"
            >{{ getDetailButtonText(scope.row.constructStateName) }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改建模数据对话框 -->
    <el-drawer
      id="dataFormDrawer"
      :title="title"
      :visible.sync="open"
      size="400px"
      style="height: 100vh"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="建模数据编号" prop="constructNo">
          <el-input
            v-model="form.constructNo"
            placeholder="请输入建模数据编号"
            disabled
          />
        </el-form-item>
        <el-form-item label="构建状态" prop="constructStateName">
          <el-select
            v-model="form.constructStateName"
            placeholder="请选择构建状态"
            disabled
          >
            <el-option
              v-for="dict in dict.type.construct_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据构建人" prop="builderName">
          <el-input
            readonly
            v-model="form.builderName"
            placeholder="请选择数据构建人"
            @click.native="userDialogVisible = true"
            @input="$refs.form.validateField('builderName')"
            class="pointer-input"
          >
            <i slot="suffix" class="el-icon-search el-input__icon"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="成分名称" prop="constituentName">
          <el-input
            readonly
            v-model="form.constituentName"
            placeholder="请选择成分名称"
            @click.native="constituentDialogVisible = true"
            @input="$refs.form.validateField('constituentName')"
            class="pointer-input"
          >
            <i slot="suffix" class="el-icon-search el-input__icon"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <!-- <el-input v-model="form.departmentName" placeholder="请输入部门名称" /> -->
          <el-select
            v-model="form.departmentName"
            size="small"
            placeholder="请选择部门"
            clearable
          >
            <el-option
              v-for="item in options.departments"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仪器编号" prop="instrumentNo">
          <el-input
            readonly
            v-model="form.instrumentNo"
            placeholder="请选择仪器编号"
            @click.native="instrumentDialogVisible = true"
            @input="$refs.form.validateField('instrumentNo')"
            class="pointer-input"
          >
            <i slot="suffix" class="el-icon-search el-input__icon"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="仪器名称" prop="instrumentName">
          <el-input
            v-model="form.instrumentName"
            placeholder="选择仪器编号后自动填充仪器名称"
            disabled
          />
        </el-form-item>
        <el-form-item label="起始波长" prop="startWavelength">
          <el-input
            v-model="form.startWavelength"
            placeholder="请输入起始波长"
          />
        </el-form-item>
        <el-form-item label="结束波长" prop="endWavelength">
          <el-input v-model="form.endWavelength" placeholder="请输入结束波长" />
        </el-form-item>
        <el-form-item label="采样时间" prop="samplingTime">
          <el-date-picker
            clearable
            v-model="form.samplingTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择采样时间"
            :editable="false"
            :picker-options="{
              disabledDate: () => false,
            }"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注" prop="remarks" style="width: 90%">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <!-- 选择仪器编号对话框 -->
    <el-dialog
      title="选择仪器编号"
      :visible.sync="instrumentDialogVisible"
      width="80%"
    >
      <instrument-data
        ref="instrumentDataRef"
        :is-row-visible="false"
        @selection-change="handleRowSelection"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseInstrument">确 定</el-button>
        <el-button @click="instrumentDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择成分名称对话框 -->
    <el-dialog
      title="选择成分名称"
      :visible.sync="constituentDialogVisible"
      width="80%"
    >
      <constituent-data
        ref="constituentDataRef"
        :is-row-visible="false"
        @selection-change="handleConstituentSelection"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseConstituent">确 定</el-button>
        <el-button @click="constituentDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择数据构建人对话框 -->
    <el-dialog
      title="选择数据构建人"
      :visible.sync="userDialogVisible"
      width="80%"
    >
      <user-data
        ref="userDataRef"
        :is-row-visible="false"
        @selection-change="handleUserSelection"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseUser">确 定</el-button>
        <el-button @click="userDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listConstruct,
  getConstruct,
  delConstruct,
  addConstruct,
  updateConstruct,
} from "@/api/model/construct";
import { listDept } from "@/api/system/dept";
import { listData } from "@/api/instrument/data";
import { listData as listConstituent } from "@/api/constituent/data";
import { listUser } from "@/api/system/user";
import InstrumentData from "@/views/instrument/data/index.vue";
import ConstituentData from "@/views/constituent/data/index.vue";
import UserData from "@/views/system/user/select.vue";
import { listEnv_spectrum } from "@/api/spectrum/env_spectrum";

export default {
  name: "Construct",
  dicts: ["construct_state"],
  props: {
    isRowVisible: {
      type: Boolean,
      default: true,
    },
    getFinishedData: {
      type: Boolean,
      default: false,
    },

  },
  components: {
    InstrumentData,
    ConstituentData,
    UserData,
  },
  data() {
    return {
      selectedInstrumentData: null, // 选中的仪器数据
      instrumentDialogVisible: false,
      selectedConstituentData: null, // 选中的成分数据
      constituentDialogVisible: false,
      selectedUserData: null, // 选中的用户数据
      userDialogVisible: false,

      envSpectrumData: [],
      options: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 建模数据表格数据
      constructList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        constructNo: null,
        constituentId: null,
        constituentName: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        startWavelength: null,
        endWavelength: null,
        samplingTime: null,
        builderId: null,
        builderName: null,
        constructStateCode: null,
        constructStateName: null,
        abnormalEliminationCode: null,
        abnormalEliminationName: null,
        dataPartitioningCode: null,
        dataPartitioningName: null,
        envSpectrumId: null,
        envSpectrumNo: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        constituentId: [
          { required: true, message: "成分id不能为空", trigger: "blur" },
        ],
        constituentName: [
          { required: true, message: "成分名称不能为空", trigger: "blur" },
        ],
        departmentName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "部门id不能为空", trigger: "blur" },
        ],
        instrumentId: [
          { required: true, message: "仪器id不能为空", trigger: "blur" },
        ],
        instrumentNo: [
          { required: true, message: "仪器编号不能为空", trigger: "blur" },
        ],
        instrumentName: [
          { required: true, message: "仪器名称不能为空", trigger: "blur" },
        ],
        startWavelength: [
          { required: true, message: "起始波长不能为空", trigger: "blur" },
        ],
        endWavelength: [
          { required: true, message: "结束波长不能为空", trigger: "blur" },
        ],
        samplingTime: [
          { required: true, message: "采样时间不能为空", trigger: "blur" },
        ],
        builderId: [
          { required: true, message: "数据构建人id不能为空", trigger: "blur" },
        ],
        builderName: [
          { required: true, message: "数据构建人不能为空", trigger: "blur" },
        ],
        constructStateCode: [
          { required: true, message: "构建状态代码不能为空", trigger: "blur" },
        ],
        constructStateName: [
          { required: true, message: "构建状态不能为空", trigger: "change" },
        ],
        isDelete: [
          { required: true, message: "是否删除不能为空", trigger: "blur" },
        ],
        creatorId: [
          { required: true, message: "新增人id不能为空", trigger: "blur" },
        ],
        creator: [
          { required: true, message: "新增人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "新增时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    if(this.getFinishedData){
      this.queryParams.constructStateName = "已完成";
    }
    this.getList();
    this.getDepartments(); // 新增部门数据获取
  },
  methods: {
    handleRowSelection(selection) {
      const tableRef = this.$refs.instrumentDataRef.$refs.instrumentTable;
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1];
        this.$nextTick(() => {
          tableRef.clearSelection(); // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true); // 仅保留当前选中
        });
        this.selectedInstrumentData = lastSelected;
      } else {
        this.selectedInstrumentData = selection[0] || null;
      }
      console.log("查看选中的仪器数据", this.selectedInstrumentData);
    },
    chooseInstrument() {
      const selectedInstrument = this.selectedInstrumentData;
      if (selectedInstrument) {
        this.$set(this.form, "instrumentId", selectedInstrument.instrumentId);
        this.$set(this.form, "instrumentNo", selectedInstrument.instrumentNo);
        this.$set(
          this.form,
          "instrumentName",
          selectedInstrument.instrumentName
        );

        // 手动清除验证错误
        this.$nextTick(() => {
          this.$refs.form.clearValidate([
            "instrumentId",
            "instrumentNo",
            "instrumentName",
          ]);
        });

        this.instrumentDialogVisible = false; // 关闭对话框
      } else {
        this.$modal.msgError("请先选择一个仪器");
      }
    },
    handleConstituentSelection(selection) {
      // 限制只能选择一个成分
      const tableRef = this.$refs.constituentDataRef.$refs.constituentTable;
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1];
        this.$nextTick(() => {
          tableRef.clearSelection(); // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true); // 仅保留当前选中
        });
        this.selectedConstituentData = lastSelected;
      } else {
        this.selectedConstituentData = selection[0] || null;
      }
      console.log("查看选中的成分数据", this.selectedConstituentData);
    },
    handleUserSelection(selection) {
      // 限制只能选择一个用户
      const tableRef = this.$refs.userDataRef.$refs.userTable;
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1];
        this.$nextTick(() => {
          tableRef.clearSelection(); // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true); // 仅保留当前选中
        });
        this.selectedUserData = lastSelected;
      } else {
        this.selectedUserData = selection[0] || null;
      }
      console.log("查看选中的用户数据", this.selectedUserData);
    },
    chooseUser() {
      const selectedUser = this.selectedUserData;
      if (selectedUser) {
        this.$set(this.form, "builderId", selectedUser.userId);
        this.$set(this.form, "builderName", selectedUser.userName);

        // 手动清除验证错误
        this.$nextTick(() => {
          this.$refs.form.clearValidate(["builderId", "builderName"]);
        });

        this.userDialogVisible = false; // 关闭对话框
      } else {
        this.$modal.msgError("请先选择一个用户");
      }
    },
    chooseConstituent() {
      const selectedConstituent = this.selectedConstituentData;
      if (selectedConstituent) {
        this.$set(
          this.form,
          "constituentId",
          selectedConstituent.constituentId
        );
        this.$set(
          this.form,
          "constituentName",
          selectedConstituent.constituentName
        );

        // 手动清除验证错误
        this.$nextTick(() => {
          this.$refs.form.clearValidate(["constituentId", "constituentName"]);
        });

        this.constituentDialogVisible = false; // 关闭对话框
      } else {
        this.$modal.msgError("请先选择一个成分");
      }
    },
    getTagType(state) {
      const map = {
        暂存: "danger",
        已完成: "success",
        // 审核中: "warning",
      };
      return map[state] || "info";
    },
    /** 获取明细按钮文本 */
    getDetailButtonText(constructStateName) {
      if (constructStateName === "暂存") {
        return "新增明细";
      } else if (constructStateName === "已完成") {
        return "查看明细";
      }
      return "明细"; // 默认文本
    },
    async handleViewDetail(row) {
      console.log("row", row);

      const query = {
        baseInfo: JSON.stringify({
          constructId: row.constructId,
          constructNo: row.constructNo,
          constructStateName: row.constructStateName,
          constituent: row.constituentName,
          department: row.departmentName,
          instrumentNo: row.instrumentNo,
          instrumentName: row.instrumentName,
          creator: row.creator,
          sampleTime: row.samplingTime,
          envSpectrumId: row.envSpectrumId,
          testSize: row.testSize,
        }),
      };

      this.$router.push({
        path: "/model/construuct/construct_datail",
        query,
      });
    },

    /** 获取部门列表 */
    async getDepartments() {
      try {
        const response = await listDept(); // 替换为实际的部门列表API
        this.options.departments = response.data;
        console.log("获取部门列表成功:", response.data);
      } catch (error) {
        console.error("获取部门列表失败:", error);
      }
    },
    /** 查询建模数据列表 */
    getList() {
      this.loading = true;
      console.log("queryParams", this.queryParams);
      listConstruct(this.queryParams).then((response) => {
        this.constructList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        constructId: null,
        constructNo: null,
        constituentId: null,
        constituentName: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        startWavelength: null,
        endWavelength: null,
        samplingTime: null,
        builderId: null,
        builderName: null,
        constructStateCode: null,
        constructStateName: null,
        abnormalEliminationCode: null,
        abnormalEliminationName: null,
        dataPartitioningCode: null,
        dataPartitioningName: null,
        envSpectrumId: null,
        envSpectrumNo: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        createTime: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.constructId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.$emit("selection-change", selection);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 设置默认采样时间为当前时间
      this.form.samplingTime = this.formatDateTime(new Date());
      // 设置默认构建状态为暂存
      this.form.constructStateName = "暂存";
      this.form.constructStateCode = "01";
      // this.fastLoad();
      this.open = true;
      this.title = "添加建模数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const constructId = row.constructId || this.ids;
      getConstruct(constructId).then((response) => {
        this.form = response.data;

        // 处理采样时间格式，确保日期选择器能正确显示
        if (this.form.samplingTime) {
          console.log("原始采样时间:", this.form.samplingTime);

          // 尝试多种日期格式解析
          let date;
          if (typeof this.form.samplingTime === "number") {
            // 时间戳
            date = new Date(this.form.samplingTime);
          } else if (typeof this.form.samplingTime === "string") {
            // 字符串格式，可能包含各种格式
            date = new Date(this.form.samplingTime.replace(/-/g, "/"));
          } else {
            date = new Date(this.form.samplingTime);
          }

          if (!isNaN(date.getTime())) {
            // 格式化为 yyyy-MM-dd HH:mm:ss 格式
            this.form.samplingTime = this.formatDateTime(date);
            console.log("格式化后采样时间:", this.form.samplingTime);
          } else {
            console.warn("无法解析采样时间:", this.form.samplingTime);
            this.form.samplingTime = null;
          }
        }

        this.open = true;
        this.title = "修改建模数据";
      });
    },
    async validateAndSetBuilderId() {
      try {
        const response = await listUser({
          userName: this.form.builderName,
        });

        if (
          response.code !== 200 ||
          !response.rows ||
          response.rows.length === 0
        ) {
          this.$modal.msgError("构建人不存在或查询失败");
          return Promise.reject(); // 阻止后续流程
        }

        console.log("角色列表", response.rows[0]);
        this.form.builderId = response.rows[0].userId;
      } catch (error) {
        console.error("查询构建人失败:", error);
        this.$modal.msgError("查询构建人失败");
        return Promise.reject();
      }
    },
    async setConstituentInfo() {
      try {
        const response = await listConstituent({
          constituentName: this.form.constituentName,
        });

        if (
          response.code !== 200 ||
          !response.rows ||
          response.rows.length === 0
        ) {
          this.$modal.msgError("成分名称不存在");
          return;
        }
        this.$set(this.form, "constituentId", response.rows[0].constituentId);
        this.form.constituentName = response.rows[0].constituentName;
        console.log("成分名称ID", this.form.constituentId);
      } catch (error) {
        console.error("查询成分名称失败:", error);
        this.$modal.msgError("查询成分失败");
      }
    },
    async setInstrumentInfo() {
      try {
        const response = await listData({
          instrumentName: this.form.instrumentName,
          instrumentNo: this.form.instrumentNo,
        });

        if (response.code === 200 && response.rows?.length > 0) {
          this.form.instrumentId = response.rows[0].instrumentId;
          console.log("仪器信息", response.rows[0]);
        } else {
          this.$modal.msgError("仪器信息不存在");
          throw new Error("仪器信息不存在");
        }
      } catch (error) {
        console.error("查询仪器失败:", error);
        this.$modal.msgError("查询仪器失败");
        throw error; // 向上传递错误，阻止后续流程
      }
    },
    fastLoad() {
      this.$set(this.form, "constructNo", "111");
      this.$set(this.form, "constructStateName", "暂存");
      this.$set(this.form, "constructStateCode", "01");
      this.$set(this.form, "builderName", "ry");
      this.$set(this.form, "departmentName", "BIO-MATH");
      this.$set(this.form, "instrumentNo", "1");
      this.$set(this.form, "instrumentName", "1");
      this.$set(this.form, "constituentName", "水");
      this.$set(this.form, "startWavelength", "1");
      this.$set(this.form, "endWavelength", "2");
    },
    changeConstructState(value) {
      this.$set(
        this.form,
        "constructStateCode",
        value === "暂存" ? "01" : "02"
      );
    },
    /** 提交按钮 */
    async submitForm() {
      try {
        await new Promise((resolve, reject) => {
          this.$refs["form"].validate((valid) => {
            if (valid) resolve(true);
            else reject(new Error("表单验证失败"));
          });
        });

        // 确保采样时间格式正确
        if (this.form.samplingTime) {
          console.log("提交前采样时间:", this.form.samplingTime);
          const date = new Date(this.form.samplingTime);
          if (!isNaN(date.getTime())) {
            this.form.samplingTime = this.formatDateTime(date);
            console.log("格式化后采样时间:", this.form.samplingTime);
          }
        }

        if (this.form.constructId != null) {
          // 更新操作 - 也需要设置相关信息
          if (!this.form.constituentId && this.form.constituentName) {
            await this.setConstituentInfo();
          }
          if (!this.form.builderId && this.form.builderName) {
            await this.validateAndSetBuilderId();
          }
          if (!this.form.instrumentId && this.form.instrumentNo) {
            await this.setInstrumentInfo();
          }

          // 填入部门id
          if (this.form.departmentName && !this.form.departmentId) {
            const dept = this.options.departments.find(
              (dept) => dept.deptName === this.form.departmentName
            );
            if (dept) {
              this.form.departmentId = dept.deptId;
            }
          }

          console.log("修改表单数据", this.form);
          await updateConstruct(this.form);
          this.$modal.msgSuccess("修改成功");
        } else {
          // 新增操作
          await this.setConstituentInfo();
          await this.validateAndSetBuilderId();
          await this.setInstrumentInfo();

          // 填入部门id
          const dept = this.options.departments.find(
            (dept) => dept.deptName === this.form.departmentName
          );
          if (dept) {
            this.form.departmentId = dept.deptId;
          } else {
            this.$modal.msgError("部门不存在");
            return;
          }

          console.log("新增表单数据", this.form);
          await addConstruct(this.form);
          this.$modal.msgSuccess("新增成功");
        }

        this.open = false;
        this.getList();
      } catch (error) {
        console.error("提交失败", error);
        this.$modal.msgError(error.message || "提交失败");
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const constructIds = row.constructId || this.ids;
      this.$modal
        .confirm('是否确认删除建模数据编号为"' + constructIds + '"的数据项？')
        .then(function () {
          return delConstruct(constructIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 格式化日期时间 */
    formatDateTime(date) {
      if (!date) return null;

      let d;
      if (typeof date === "number") {
        d = new Date(date);
      } else if (typeof date === "string") {
        // 处理各种字符串格式
        d = new Date(date.replace(/-/g, "/"));
      } else {
        d = new Date(date);
      }

      if (isNaN(d.getTime())) {
        console.warn("无法格式化日期:", date);
        return null;
      }

      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      const hours = String(d.getHours()).padStart(2, "0");
      const minutes = String(d.getMinutes()).padStart(2, "0");
      const seconds = String(d.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "model/construct/export",
        {
          ...this.queryParams,
        },
        `construct_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
#dataFormDrawer .el-input {
  width: 85%; /* 输入框占满剩余宽度（匹配图片效果） */
}

.drawer-footer {
  /* width: 100%; */
  position: absolute;
  right: 10px;
  bottom: 10px;
}

.pointer-input {
  cursor: pointer;
}

.pointer-input .el-input__inner {
  cursor: pointer;
}
</style>
